<template>
  <view class="schedule-container">
    <!-- 顶部周数选择器 -->
    <view class="week-selector-container">
      <view class="week-selector">
        <text class="week-label">所在周：</text>
        <lk-week-picker
          type="date" 
          fields="week"
          :value="currentDate"
          @change="handleWeekChange"
          format="yyyy年第WW周"
          placeholder="选择周"
        ></lk-week-picker>
      </view>
    </view>

    <!-- 课程表标题 -->
    <view class="schedule-header">
      <view class="header-row">
        <view class="header-cell time-header">时间</view>
        <view class="header-cell" v-for="day in weekDays" :key="day.value">
          {{ day.label }}
        </view>
      </view>
    </view>

    <!-- 课程表内容 -->
    <scroll-view class="schedule-scroll" scroll-y="true">
      <view class="schedule-content">
        <view 
          class="schedule-row" 
          v-for="(timeSlot, index) in timeSlots" 
          :key="index"
        >
          <view class="time-cell">
            {{ timeSlot }}
          </view>
          <view 
            class="schedule-cell"
            v-for="(day, dayIndex) in weekDays" 
            :key="dayIndex"
            @click="handleCellClick(index, day.value)"
            :class="{
              'selected': isSelected(index, day.value),
              'has-course': hasCourse(index, day.value)
            }"
          >
            <view class="course-info" v-if="hasCourse(index, day.value)">
              <view class="course-name">{{ getCourseInfo(index, day.value).courseName }}</view>
              <view class="course-teacher">{{ getCourseInfo(index, day.value).teacherName }}</view>
              <view class="course-location">{{ getCourseInfo(index, day.value).location }}</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <button 
        class="save-btn" 
        type="primary"
        @click="handleSave"
        :disabled="selectedCells.length === 0"
      >
        保存课程安排
      </button>
    </view>

    <!-- 选择课程弹窗 -->
    <uni-popup ref="coursePopup" type="center" :animation="false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择课程</text>
          <uni-icons type="close" size="20" @click="closePopup"></uni-icons>
        </view>
        <uni-forms ref="courseForm" :model="courseForm">
          <!-- 课程选择 -->
          <view class="form-item">
            <text class="form-label">课程：</text>
            <uni-data-picker
              v-model="courseForm.courseId"
              :localdata="courseOptions"
              field="value"
              text-field="label"
              placeholder="请选择课程"
            ></uni-data-picker>
          </view>
          <!-- 上课地点 -->
          <view class="form-item">
            <text class="form-label">上课地点：</text>
            <uni-easyinput 
              v-model="courseForm.location" 
              placeholder="请填写上课地点"
              :border="false"
            ></uni-easyinput>
          </view>
          <!-- 结束周 -->
          <view class="form-item">
            <text class="form-label">结束周：</text>
            <uni-datetime-picker 
              type="date" 
              fields="week"
              :value="courseForm.endWeek"
              @change="handleEndWeekChange"
              format="yyyy年第WW周"
              placeholder="选择结束周"
            ></uni-datetime-picker>
            <text class="form-hint">填写后将自动保存当前周到结束周的课程安排</text>
          </view>
        </uni-forms>
        <view class="popup-footer">
          <button class="cancel-btn" @click="closePopup">取消</button>
          <button class="confirm-btn" type="primary" @click="confirmCourse">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import request from '@/utils/request'
  import lkWeekPicker from '@/uni_modules/lk-week-picker/components/lk-week-picker/lk-week-picker.vue'
  export default {
    components: {
      lkWeekPicker
    },
    data() {
      return {
        // 当前选择的日期
        currentDate: new Date().getTime(),
        // 格式化后的周数
        formattedWeek: '',
        // 星期列表
        weekDays: [
          { label: '周一', value: 'monday' },
          { label: '周二', value: 'tuesday' },
          { label: '周三', value: 'wednesday' },
          { label: '周四', value: 'thursday' },
          { label: '周五', value: 'friday' },
          { label: '周六', value: 'saturday' },
          { label: '周日', value: 'sunday' }
        ],
        // 时间段列表
        timeSlots: [
          '09:00-10:30',
          '10:30-12:00',
          '13:30-15:00',
          '15:00-16:30',
          '16:30-18:00',
          '18:00-19:30'
        ],
        // 课程数据
        courseData: [],
        // 选中的单元格
        selectedCells: [],
        // 课程选项
        courseOptions: [],
        // 课程表单
        courseForm: {
          courseId: '',
          location: '',
          endWeek: ''
        },
        // 班级ID
        classId: null
      }
    },
    onLoad() {
      // 初始化格式化周数
      this.formattedWeek = this.formatWeek(this.currentDate)
      // 获取课程数据
      this.getSchedule()
      // 获取课程选项
      this.getCourseOptions()
    },
    methods: {
      // 格式化周数
      formatWeek(date) {
        const d = new Date(date)
        const year = d.getFullYear()
        // 计算当前是第几周
        const firstDay = new Date(year, 0, 1)
        const pastDays = (d - firstDay) / (1000 * 60 * 60 * 24)
        const weekNum = Math.ceil((pastDays + firstDay.getDay() + 1) / 7)
        return `${year} 第 ${weekNum} 周`
      },
      // 周数变化
      handleWeekChange(e) { 
        this.currentDate = value
        this.formattedWeek = this.formatWeek(this.currentDate)
        // 重新获取课程数据
        this.getSchedule()
      },
      // 结束周变化
      handleEndWeekChange(e) {
        this.courseForm.endWeek = e.detail.value
      },
      // 获取课程数据
      getSchedule() {
        // 重置选中的单元格
        this.selectedCells = []
        // 这里应该调用后端API获取课程数据，暂时使用模拟数据
        this.courseData = [
          {
            time: '09:00-10:30',
            monday: {
              courseName: '绘画初级课程',
              teacherName: '张老师',
              location: '绘画教室1'
            },
            wednesday: {
              courseName: '书法高级课程',
              teacherName: '李老师',
              location: '书法教室1'
            }
          },
          {
            time: '10:30-12:00',
            tuesday: {
              courseName: '舞蹈基础课程',
              teacherName: '王老师',
              location: '舞蹈教室1'
            },
            thursday: {
              courseName: '音乐启蒙课程',
              teacherName: '刘老师',
              location: '音乐教室1'
            }
          }
        ]
      },
      // 获取课程选项
      getCourseOptions() {
        // 这里应该调用后端API获取课程选项，暂时使用模拟数据
        this.courseOptions = [
          { value: '1', label: '绘画初级课程' },
          { value: '2', label: '书法高级课程' },
          { value: '3', label: '舞蹈基础课程' },
          { value: '4', label: '音乐启蒙课程' }
        ]
      },
      // 处理单元格点击
      handleCellClick(rowIndex, day) {
        // 检查该单元格是否已有课程
        if (this.hasCourse(rowIndex, day)) {
          uni.showToast({
            title: '该时间段已有课程安排',
            icon: 'none'
          })
          return
        }
        
        // 切换选中状态
        const cellKey = `${rowIndex}-${day}`
        const index = this.selectedCells.indexOf(cellKey)
        if (index > -1) {
          this.selectedCells.splice(index, 1)
        } else {
          this.selectedCells.push(cellKey)
        }
      },
      // 检查单元格是否被选中
      isSelected(rowIndex, day) {
        const cellKey = `${rowIndex}-${day}`
        return this.selectedCells.indexOf(cellKey) > -1
      },
      // 检查单元格是否已有课程
      hasCourse(rowIndex, day) {
        const course = this.courseData[rowIndex]
        return course && course[day] && course[day].courseName
      },
      // 获取课程信息
      getCourseInfo(rowIndex, day) {
        return this.courseData[rowIndex][day]
      },
      // 处理保存按钮点击
      handleSave() {
        if (this.selectedCells.length === 0) {
          uni.showToast({
            title: '请至少选择一个时间段',
            icon: 'none'
          })
          return
        }
        // 打开课程选择弹窗
        this.$refs.coursePopup.open()
      },
      // 确认课程
      confirmCourse() {
        // 验证表单
        if (!this.courseForm.courseId) {
          uni.showToast({
            title: '请选择课程',
            icon: 'none'
          })
          return
        }
        if (!this.courseForm.location) {
          uni.showToast({
            title: '请填写上课地点',
            icon: 'none'
          })
          return
        }
        
        // 这里应该调用后端API保存课程安排
        console.log('保存课程安排', {
          selectedCells: this.selectedCells,
          courseForm: this.courseForm
        })
        
        // 保存成功后关闭弹窗，刷新课程数据
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        this.$refs.coursePopup.close()
        this.getSchedule()
      },
      // 关闭弹窗
      closePopup() {
        this.$refs.coursePopup.close()
      }
    }
  }
</script>

<style scoped>
  .schedule-container {
    background-color: #f5f5f5;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }

  /* 周数选择器 */
  .week-selector-container {
    background-color: white;
    padding: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  }

  .week-selector {
    display: flex;
    align-items: center;
  }

  .week-label {
    font-size: 14px;
    color: #333;
    margin-right: 10px;
  }

  .week-picker {
    font-size: 14px;
    color: #333;
    padding: 5px 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }

  /* 课程表标题 */
  .schedule-header {
    background-color: #46a6ff;
    color: white;
    font-weight: bold;
  }

  .header-row {
    display: flex;
  }

  .header-cell {
    flex: 1;
    text-align: center;
    padding: 10px 5px;
    font-size: 13px;
  }

  .time-header {
    flex: 0 0 80px;
    background-color: #3a91d8;
  }

  /* 课程表内容 */
  .schedule-scroll {
    flex: 1;
    overflow-y: auto;
  }

  .schedule-content {
    background-color: white;
  }

  .schedule-row {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
  }

  .time-cell {
    flex: 0 0 80px;
    text-align: center;
    padding: 15px 5px;
    font-size: 12px;
    background-color: #f5f7fa;
    border-right: 1px solid #e4e7ed;
  }

  .schedule-cell {
    flex: 1;
    text-align: center;
    padding: 10px 5px;
    border-right: 1px solid #e4e7ed;
    min-height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    cursor: pointer;
  }

  .schedule-cell:last-child {
    border-right: none;
  }

  .schedule-cell:active {
    background-color: #e6f7ff;
  }

  .selected {
    background-color: #e6f7ff !important;
    box-shadow: inset 0 0 0 2px #46a6ff;
  }

  .has-course {
    background-color: #f0f9eb;
  }

  .course-info {
    display: flex;
    flex-direction: column;
    gap: 3px;
  }

  .course-name {
    font-size: 12px;
    font-weight: bold;
    color: #333;
  }

  .course-teacher {
    font-size: 11px;
    color: #666;
  }

  .course-location {
    font-size: 11px;
    color: #46a6ff;
  }

  /* 底部操作栏 */
  .bottom-bar {
    background-color: white;
    padding: 10px;
    box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.08);
  }

  .save-btn {
    width: 100%;
    margin: 0;
  }

  /* 弹窗样式 */
  .popup-content {
    background-color: white;
    border-radius: 10px;
    padding: 20px;
    width: 90%;
    max-width: 400px;
  }

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .popup-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }

  .popup-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  /* 表单样式 */
  .form-item {
    margin-bottom: 20px;
  }

  .form-label {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    display: block;
  }

  .form-hint {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
  }

  .end-week-picker {
    font-size: 14px;
    color: #333;
    padding: 10px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }
</style>